<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkRoom\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactRoomContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 群内成员.
 *
 * Class MemberIndex
 * @Controller
 */
class MemberIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContact;

    /**
     * @Inject
     * @var WorkContactRoomContract
     */
    protected $workContactRoom;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Inject
     * @var WorkRoomContract
     */
    protected $workRoom;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployee;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/workRoom/memberIndex", methods="get")
     */
    public function handle(): array
    {
        // 接收参数
        $params = [
            'roomId' => (int) $this->request->input('roomId'),
            'name' => $this->request->input('name', ''),
        ];
        // 校验参数
        $this->validated($params);
        $owner = $this->workRoom->getWorkRoomById($params['roomId'], ['owner_id']);
        $roomEmployee = $this->workContactRoom->getWorkContactRoomsByRoomIdEmployee($params['roomId'], ['employee_id']);
        $room = $this->workContactRoom->getWorkContactRoomsByRoomId(
            $params['roomId'],
            ['id', 'contact_id', 'employee_id', 'join_scene', 'type', 'join_time', 'role_type', 'status']
        );

        foreach ($room as $k => $v) {
            if ($v['status'] == 2) {
                unset($room[$k]);
                continue;
            }

            $room[$k]['isOwner'] = 0; // 群主（0：否，1：是）
            $room[$k]['inviter'] = ''; // 邀请者
            $room[$k]['corpName'] = ''; // 企业名称
            if ($v['contactId'] > 0) {
                $contactEmployee = $this->workContactEmployee->getWorkContactEmployeesByContactIdEmployeeIds($v['contactId'], array_column($roomEmployee, 'employeeId'), ['employee_id']);
                if (! empty($contactEmployee)) {
                    $inviterEmployee = $this->workEmployee->getWorkEmployeeById($contactEmployee['employeeId'], ['name']);
                    $room[$k]['inviter'] = ! empty($inviterEmployee) ? $inviterEmployee['name'] : '';
                }
                $contact = $this->workContact->getWorkContactById($v['contactId'], ['id', 'wx_external_userid', 'name', 'avatar']);
                if (! $contact) {
                    unset($room[$k]);
                    continue;
                }
                $room[$k]['contactId'] = $contact['id'];
                $room[$k]['wxExternalUserid'] = $contact['wxExternalUserid'];
                $room[$k]['name'] = $contact['name'];
                $room[$k]['avatar'] = file_full_url($contact['avatar']);
                $room[$k]['roleType'] = $v['roleType'] === 0 ? 3 : $v['roleType'];
            }
            if ($v['employeeId'] > 0) {
                if ($v['employeeId'] === $owner['ownerId']) {
                    $room[$k]['isOwner'] = 1;
                }
                $employee = $this->workEmployee->getWorkEmployeeByIdWithTrashed($v['employeeId'], ['corp_id', 'name', 'avatar']);
                if (! $employee) {
                    unset($room[$k]);
                    continue;
                }

                $room[$k]['name'] = $employee['name'];
                $room[$k]['avatar'] = file_full_url($employee['avatar']);
                $room[$k]['corpName'] = $this->corpService->getCorpById($employee['corpId'], ['name'])['name'];
                $room[$k]['roleType'] = $v['roleType'] === 0 ? 1 : $v['roleType'];
            }
            if ($v['contactId'] === 0 && $v['employeeId'] === 0) {
                unset($room[$k]);
                continue;
            }
            # # 名称搜索
            if (! empty($params['name']) && ! str_contains($room[$k]['name'], $params['name'])) {
                unset($room[$k]);
            }
        }

        $first = [];
        $other = [];
        foreach ($room as $item) {
            if ($item['isOwner'] === 1) {
                $first[] = $item;
            } else {
                $other[] = $item;
            }
        }
        return array_merge($first, $other);
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'roomId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'roomId.required' => '客户群id 必传',
        ];
    }
}
